﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class StudentMarksControl : UserControl
    {
        private readonly Business.Business _business;

        public StudentMarksControl()
        {
            InitializeComponent();

            _business = Main.Main.Instance.IgmBusiness;
        }

        public void StudentMarksControlLoad(object sender, EventArgs e)
        {
            LoadKindMark();
            LoadStudent();
            LoadStudentMark();
            Dock = DockStyle.Top;
        }

        private void LoadKindMark()
        {
            cboKindMarks.DataSource = _business.GetListKindMark();
            cboKindMarks.DisplayMember = PropertiesConstants.Name;
            cboKindMarks.ValueMember = PropertiesConstants.Id;
        }
        public void LoadStudent()
        {
            cboStudent.DataSource = _business.GetListStudent();
            cboStudent.DisplayMember = PropertiesConstants.Name;
            cboStudent.ValueMember = PropertiesConstants.Id;
        }

        /// <summary>
        /// 
        /// </summary>
        public void LoadStudentMark()
        {
            dgvStudentMarks.DataSource = _business.GetListStudentMarkByKindMarkId(((KindMark)cboKindMarks.SelectedItem).Id);

            DataGridViewHelper.ShowHideColumns(dgvStudentMarks,
                                               new[] { PropertiesConstants.IsChecked, "StudentCode", "Mark", "IsDebt", "StudentName", "Index" });
            DataGridViewHelper.ShowIsCheck(dgvStudentMarks);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudentMarks, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvStudentMarks, new[] { "IsChecked", "StudentCode", "Mark", "IsDebt", "StudentName", "Index" },
                                                   new[] { "Chọn", "Mã sinh viên", "Điểm", "Có bị nợ môn", "Tên sinh viên", "Xếp hạng" });

            if (dgvStudentMarks != null)
            {
                dgvStudentMarks.Columns["Index"].DisplayIndex = 1;
                dgvStudentMarks.Columns["StudentCode"].DisplayIndex = 2;
                dgvStudentMarks.Columns["StudentName"].DisplayIndex = 3;
            }

            StudentMarkCurrentRowChanged();
        }

        private void StudentMarkCurrentRowChanged()
        {
            if (dgvStudentMarks.CurrentRow != null)
            {
                cboStudent.Text = dgvStudentMarks.CurrentRow.Cells["StudentName"].Value.ToString();
                txtMark.Text = dgvStudentMarks.CurrentRow.Cells["Mark"].Value.ToString();
                ckbDebt.Checked = (bool)dgvStudentMarks.CurrentRow.Cells["IsDebt"].Value;
            }

            else
            {
                cboStudent.Text = txtMark.Text = string.Empty;
                ckbDebt.Checked = false;
            }
        }

        private void DgvStudentMarksCurrentCellChanged(object sender, EventArgs e)
        {
            StudentMarkCurrentRowChanged();
        }

        private void DgvStudentMarksCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvStudentMarks == null ||
               dgvStudentMarks.Columns[(string)typeof(StudentMark).Properties().IsChecked] == null ||
               dgvStudentMarks.Columns[(string)typeof(StudentMark).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvStudentMarks[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvStudentMarks[e.ColumnIndex, e.RowIndex].Value;

            ckbAllStudentMarks.Checked = DataGridViewHelper.AllRowsIsCheck(dgvStudentMarks);
        }

        private void CkbAllStudentMarksCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvStudentMarks, ckbAllStudentMarks.Checked);
        }

        private void ReloadStudentMark(StudentMark stundentmark)
        {
            LoadStudentMark();
            DataGridViewHelper.SetDgvCurrentCell(dgvStudentMarks, stundentmark.StudentCode);
            StudentMarkCurrentRowChanged();
        }

        /// <summary>
        /// Event click button Add Student
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddStudentMarkClick(object sender, EventArgs e)
        {
            try
            {
                var studentmark = new StudentMark
                {
                    IdKindMark = Convert.ToInt32(((KindMark)cboKindMarks.SelectedItem).Id),
                    IdStudent = Convert.ToInt32(((Student)cboStudent.SelectedItem).Id),
                    Mark = Convert.ToInt32(txtMark.Text.Trim()),
                    IsDebt = ckbDebt.Checked,
                };

                string message;

                if (_business.AddStudentMarkValidator(studentmark, out message))
                {
                    _business.AddStudentMark(studentmark);

                    ReloadStudentMark(studentmark);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click edit 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditStudentMarkClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvStudentMarks.CurrentRow != null)
                {
                    var mark = 0;
                    if (!string.IsNullOrEmpty(txtMark.Text.Trim()))
                        mark = Convert.ToInt32(txtMark.Text.Trim());
                    var studentmark = new StudentMark
                    {
                        Id = Convert.ToInt32(dgvStudentMarks.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        IdKindMark = Convert.ToInt32(((KindMark)cboKindMarks.SelectedItem).Id),
                        IdStudent = Convert.ToInt32(((Student)cboStudent.SelectedItem).Id),
                        Mark = mark,
                        IsDebt = ckbDebt.Checked
                    };
                    string message;
                    if (_business.EditStudentMarkValidator(studentmark, out message))
                    {
                        if (!_business.EditStudentMark(studentmark))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadStudentMark(studentmark);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Student Mark
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteStudentMarkClick(object sender, EventArgs e)
        {
            try
            {
                var studentmarks = new List<StudentMark>();
                string message;

                for (var i = 0; i < dgvStudentMarks.RowCount; i++)
                {
                    if (!(bool)dgvStudentMarks[(string)typeof(StudentMark).Properties().IsChecked, i].Value) continue;

                    studentmarks.Add(new StudentMark
                    {
                        Id = (int)dgvStudentMarks[(string)typeof(StudentMark).Properties().Id, i].Value,
                        IdKindMark = Convert.ToInt32(dgvStudentMarks["IdKindMark", i].Value),
                        IdStudent = Convert.ToInt32(dgvStudentMarks["IdStudent", i].Value),
                        Mark = Convert.ToDouble(dgvStudentMarks["Mark", i].Value),
                        IsDebt = (bool)dgvStudentMarks["IsDebt", i].Value,
                    });
                }
                if (studentmarks.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteStudentMarksValidator(studentmarks, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các điểm đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteStudentMarks(studentmarks);
                        ReloadStudentMark(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void PicSortMarkClick(object sender, EventArgs e)
        {
            dgvStudentMarks.DataSource = _business.SortStudentMark(((KindMark)cboKindMarks.SelectedItem).Id);

            // Save index after order

            for (var i = 0; i < dgvStudentMarks.RowCount; i++)
                dgvStudentMarks.Rows[i].Cells["Index"].Value = i + 1;
        }

        private void CboKindMarksSelectionChangeCommitted(object sender, EventArgs e)
        {
            LoadStudentMark();
        }

        private void ImportDataClick(object sender, EventArgs e)
        {
            var frm= new FormImportedData();
            frm.ReLoadStudentMark += () =>
                                         {
                                             LoadStudent();
                                             LoadStudentMark();
                                         };
            frm.ShowDialog();
        }
        
        private void TxtMarkLeave(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMark.Text)) return;
            double value;
            if ((double.TryParse(txtMark.Text, out value) && value >= 0) && value <= 10) return;
            MessageBox.Show(@"Điểm bạn nhập không hợp lệ. Điểm cần 0 <= x <= 10");
            txtMark.Focus();
            txtMark.SelectAll();
        }

        private void TxtMarkKeyPress(object sender, KeyPressEventArgs e)
        {
           if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
            {
                e.Handled = true;
            }
        }
    }
}
